package cn.edu.zut.soft.graduate.controller;

import cn.edu.zut.soft.basic.core.constant.Alternative;
import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.graduate.basic.bo.FormatIssueBO;
import cn.edu.zut.soft.graduate.core.constant.IssueKind;
import cn.edu.zut.soft.graduate.core.constant.IssuePhase;
import cn.edu.zut.soft.graduate.core.constant.IssueSource;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.model.Impl.Issue;
import cn.edu.zut.soft.graduate.core.query.IssueQuery;
import cn.edu.zut.soft.graduate.core.vo.*;
import cn.edu.zut.soft.graduate.log.IssueSearchLogServiceImpl;
import cn.edu.zut.soft.graduate.model.HChildTopic;
import cn.edu.zut.soft.graduate.model.HistoryFormatIssue;
import cn.edu.zut.soft.graduate.topicCenter.bo.DeclareBO;
import cn.edu.zut.soft.graduate.topicCenter.bo.IssueBO;
import cn.edu.zut.soft.graduate.topicCenter.pojo.ConfirmInfo;
import cn.edu.zut.soft.graduate.userCenter.bo.InfoBO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chuchuang on 16/10/26.
 */
@Controller
@RequestMapping("issue")
public class IssueController extends BaseController {

    private static final List<IssuePhase> statusSet = Arrays.asList(IssuePhase.saveIng, IssuePhase.auditIng, IssuePhase.auditErrorIng, IssuePhase.auditSuccessIng, IssuePhase.chooseIng, IssuePhase.finish);


    // FIXME: 2016/11/1 修改为动态数据配置
    private final static Map<String, Technology> technologyMap = new HashMap<String, Technology>() {
        private static final long serialVersionUID = 6046417821940256391L;

        {
            put("1", new Technology("1", "Java EE"));
            put("2", new Technology("2", "PHP"));
            put("3", new Technology("3", "Ios"));
            put("4", new Technology("4", "Android"));
            put("5", new Technology("5", "前端"));
            put("6", new Technology("6", "网络营销"));
            put("7", new Technology("7", "ASP.NET"));
            put("8", new Technology("8", "其他"));
        }
    };
    private final static Map<String, String> issueSourceMap = IssueSource.getMap();
    private final static Map<String, String> issueKindMap = IssueKind.getMap();
    private final static Map<String, String> issuePhaseMap = IssuePhase.getMap();

    @Autowired
    private IssueSearchLogServiceImpl issueSearchLogService;

    @Resource
    private IssueBO issueBO;

    @Resource
    private FormatIssueBO formatIssueBO;

    @Resource
    private DeclareBO declareBO;

    @Resource
    private InfoBO infoBO;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(String jsonData, HttpSession session) {
        if (jsonData == null) {
            return CommonResult.errorReturn("数据不存在,请重新输入数据");
        }
        //反向解密数据
        jsonData = StringEscapeUtils.unescapeHtml4(jsonData);
        IssueVO issueVO = JSON.parseObject(jsonData, IssueVO.class);
        //做信息效验
        if (StringUtils.isBlank(issueVO.getIssue().getTitle())) {
            return CommonResult.errorReturn("名称不能为空,请重新输入数据");
        }
        if (StringUtils.isBlank(issueVO.getIssue().getType())) {
            return CommonResult.errorReturn("课题类型不能为空,请重新输入数据");
        }
        LoginVO loginVO = ((LoginVO) session.getAttribute("user"));
        issueVO.getIssue().setSource(IssueSource.findIssueSource(Role.valueOf(loginVO.getRole())));
        //设定所属者
        // FIXME: 16/11/8
//        issueVO.getIssue().setOwner(JSONObject.toJSONString(new Owner(loginVO.getId(),loginVO.getName(),loginVO.getRole())));
        issueVO.getIssue().setIdentityId(loginVO.getId());
        issueVO.getIssue().setIdentityName(loginVO.getName());
        issueVO.getIssue().setIdentityRole(Role.valueOf(loginVO.getRole()));
        if (Role.tea == Role.valueOf(loginVO.getRole())) {
            issueVO.getIssueContent().setSchoolTeacher(new SchoolTeacher(loginVO.getId(), loginVO.getName()));
        }
        return issueBO.save(issueVO, loginVO);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult get(@PathVariable("id") String id) {
        Issue issue = issueBO.get(Integer.valueOf(id));
        if (issue != null) {
            IssueContent issueContent = JSON.parseObject(issue.getContent(), IssueContent.class);
            issue.setContent(null);
            return CommonResult.successReturn(new IssueVO(issue, issueContent));
        }
        return CommonResult.errorReturn("当前课题不存在");
    }

    @RequestMapping(value = "{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(String jsonData, HttpSession session, @PathVariable("id") String id) {
        if (jsonData == null) {
            return CommonResult.errorReturn("数据不存在,请重新输入数据");
        }
        //反向解密数据
        jsonData = StringEscapeUtils.unescapeHtml4(jsonData);
        IssueVO issueVO = JSON.parseObject(jsonData, IssueVO.class);
        if (issueVO == null) {
            return CommonResult.errorReturn("数据错误,请重新核验数据");
        }
        //设定id
        issueVO.getIssue().setId(Integer.valueOf(id));
        return issueBO.update(issueVO, ((LoginVO) session.getAttribute("user")).getName());
    }

    @RequestMapping(value = "/list/{role}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult find(HttpServletRequest request, HttpServletResponse response, IssueQuery issueQuery, @PathVariable("role") Role role) {
        issueQuery.setIdentityRole(role);
        // FIXME: 16/11/30 日志记录  希望之后采用其他方式
        Map<Object,Object> map = new HashMap<>();
        map.put(IssueQuery.class,issueQuery);
        issueSearchLogService.behaviour(request,response, map);
        if (issueQuery.getIssuePhase() == null && CollectionUtils.isEmpty(issueQuery.getIssuePhaseList())){
            issueQuery.setIssuePhaseList(IKEY.statusSet);
        }
        return issueBO.findByQueryTakeWitness(issueQuery);
    }

    @RequestMapping(value = "/querySelf")
    @ResponseBody
    public CommonResult<List<Issue>> querySelf(HttpSession session, IssueQuery issueQuery) {
        LoginVO loginVO = (LoginVO) session.getAttribute("user");
        issueQuery.setSchoolTeaId(loginVO.getId());
        if (StringUtils.isBlank(issueQuery.getOrderByClause())) {
            issueQuery.setOrderByClause("create_time desc");
        }
        issueQuery.clear();
        issueQuery.setIssuePhaseList(statusSet);
        return issueBO.findByQuery(issueQuery);
    }

    @RequestMapping(value = "/issueOperate/{handle}/{id}")
    @ResponseBody
    public CommonResult issueOperate(HttpSession session, @PathVariable("id") String id, @PathVariable("handle") IssuePhase.Handle handle) {
        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
        Assert.notNull(loginVO, "用户未登录,请重新登录");
        return CommonResult.successReturn(issueBO.changeIssuePhase(loginVO, Integer.parseInt(id), handle));
    }

    @ResponseBody
    @RequestMapping(value = "/issueRemark/{handle}/{id}")
    public CommonResult issueRemarkRefuse(HttpSession session, @PathVariable("id") String id, @PathVariable("handle") IssuePhase.Handle handle, @RequestParam("remark") String remark) {
        LoginVO sessionLogin = (LoginVO) session.getAttribute("user");
        if (StringUtils.isEmpty(id)) {
            return CommonResult.errorReturn("数据错误");
        }
        String remarkTime = null;
        Format format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (StringUtils.isNotBlank(remark)) {
            remarkTime = remark + "--时间:" + format.format(new Date()) + "--创建者:" + sessionLogin.getName();
        } else {
            remarkTime = "您的题目已被操作,详细情况咨询创建者! " + "--时间:" + format.format(new Date()) + "--创建者:" + sessionLogin.getName();
        }

        IssueVO result = issueBO.refuseAndRemark(sessionLogin, handle, id, sessionLogin.getName(), remarkTime);
        if (result == null) {
            return CommonResult.errorReturn("数据错误");
        }
        return CommonResult.successReturn(result);
    }

    @RequestMapping("gainTechnologyAll")
    @ResponseBody
    public CommonResult gainTechnologyAll() {
        return CommonResult.successReturn(technologyMap);
    }

    @RequestMapping("gainIssueSource")
    @ResponseBody
    public CommonResult gainIssueSources() {
        return CommonResult.successReturn(issueSourceMap);
    }

    @RequestMapping("gainIssueKind")
    @ResponseBody
    public CommonResult gainIssueKind() {
        return CommonResult.successReturn(issueKindMap);

    }

    @RequestMapping("gainIssuePhase")
    @ResponseBody
    public CommonResult gainIssuePhase() {
        return CommonResult.successReturn(issuePhaseMap);
    }


    @ResponseBody
    @RequestMapping("/history")
    public CommonResult historyIssue(HttpServletRequest request) {

        LoginVO session = (LoginVO) request.getSession().getAttribute("user");
        if (session.getName() == null) {
            return CommonResult.errorReturn("数据错误");
        }
        List<HistoryFormatIssue> result = formatIssueBO.formartIssueByTea(session.getName());
        return CommonResult.successReturn(result);
    }

    @ResponseBody
    @RequestMapping("/historyId")
    public CommonResult HistoryTopicById(@RequestParam("id") Integer id) {
        if (id == null) {
            return null;
        }
        HistoryFormatIssue historyFormatIssue = formatIssueBO.formartIssueById(id);
        return CommonResult.successReturn(historyFormatIssue);
    }

    @RequestMapping("/historyToSave")
    public String HistoryToSave(HttpServletRequest request, @RequestParam("id") Integer id) {
        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");
        if (id == null) {
            return "redirect:/issue/history";
        }
        HistoryFormatIssue hfi = formatIssueBO.formartIssueById(id);
        if (hfi == null) {
            return "redirect:/issue/history";
        }
        IssueVO issueVO = formatHistory(hfi);
        //设定所属者
        // FIXME: 16/11/8
//        issueVO.getIssue().setOwner(JSONObject.toJSONString(new Owner(loginVO.getId(),loginVO.getName(),loginVO.getRole())));
        assert issueVO != null;
        issueVO.getIssue().setIdentityId(loginVO.getId());
        issueVO.getIssue().setIdentityName(loginVO.getName());
        issueVO.getIssue().setIdentityRole(Role.valueOf(loginVO.getRole()));
        if (Role.tea == Role.valueOf(loginVO.getRole())) {
            issueVO.getIssueContent().setSchoolTeacher(new SchoolTeacher(loginVO.getId(), loginVO.getName()));
        }
        //插入状态
        issueVO.getIssue().setSource(IssueSource.findIssueSource(Role.valueOf(loginVO.getRole())));

        CommonResult<IssueVO> insetResult = issueBO.save(issueVO, loginVO);
        if (!insetResult.isSuccess()) {
            return "redirect:/issue/history";
        }
        ///tea/declare?issueId=' + node.id
        return "redirect:/tea/declare?issueId=" + insetResult.getData().getIssue().getId();
    }

    @ResponseBody
    @RequestMapping("issue_audit_userId")
    public CommonResult issueAuditByUserId(@RequestParam("userId") Integer userId, @RequestParam("role") String role) {
        if (userId == null) {
            return CommonResult.errorReturn("数据错误");
        }
        return CommonResult.successReturn(issueBO.getExpertIssueByTeaID(userId, role));
    }


    @ResponseBody
    @RequestMapping("/choose/stuGroup/{id}/{alternative}")
    public CommonResult chooseStuGroupByDeclare(HttpServletRequest request, @PathVariable("id") Integer declareId, @PathVariable("alternative") Alternative alternative) {
        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");
        if (declareId == null) {
            return CommonResult.errorReturn("System error");
        }
        ConfirmInfo confirmInfo = declareBO.TeaConfirm(loginVO, declareId, alternative);
        if (confirmInfo == null) {
            return CommonResult.errorReturn("System error");
        }
        return CommonResult.successReturn(confirmInfo);
    }

    private IssueVO formatHistory(HistoryFormatIssue hfi) {
        IssueVO result = new IssueVO();
        Issue issue = new Issue();
        IssueContent issueContent = new IssueContent();
        List<Task> tasks = new ArrayList<>();
        if (hfi == null) {
            return null;
        }
        //标题
        issue.setTitle(hfi.getTitle());
        //类型
        issue.setType(hfi.getType());
        //任务数
        issue.setTaskSize(hfi.getTask_size());
        //课题性质
        issue.setKind(IssueKind.valueOf(hfi.getKind()));
        //项目背景
        issueContent.setBackground(hfi.getBackground());
        //子标题加内容
        if (hfi.getTask() != null && hfi.getTask().size() > 0) {
            for (HChildTopic h : hfi.getTask()) {
                Task task = new Task();
                task.setTitle(h.getName());
                task.setContent(h.getContent());
                tasks.add(task);
            }
            issueContent.setTaskList(tasks);
        }
        result.setIssue(issue);
        result.setIssueContent(issueContent);

        return result;
    }

    /**
     * 功能描述:分配子标题
     * @param request
     * @param topId
     * @param childId
     * @param id
     * @return
     */

    @ResponseBody
    @RequestMapping("/assignChildTop")
    public CommonResult assignChildTop(HttpServletRequest request,@RequestParam("topId") Integer topId,@RequestParam("childId") String childId, @RequestParam("stuId") Integer id){
        if (StringUtils.isEmpty(childId) || id == null || topId == null){
            return CommonResult.errorReturn("System error");
        }
        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");
        if (loginVO == null) {
            return CommonResult.errorReturn("请重新登录");
        }
        Issue issue = issueBO.assignChildTopic(topId, childId, id, loginVO);
        if (issue != null){
            return CommonResult.successReturn(issue);
        }
        return CommonResult.errorReturn("System error");
    }

    @RequestMapping("/restChildTop")
    public ModelAndView restChildTop(HttpServletRequest request,@RequestParam("topId") Integer topId,@RequestParam("childId") String childId, @RequestParam("stuId") Integer id){
        if (StringUtils.isEmpty(childId) || id == null || topId == null){
            return new ModelAndView("redirect:/tea/guide");
        }
        LoginVO loginVO = (LoginVO) request.getSession().getAttribute("user");
        if (loginVO == null) {
            return new ModelAndView("redirect:/login");
        }
        Issue issue = issueBO.restChildTopic(topId, childId, id, loginVO);
        return new ModelAndView("redirect:/tea/guide");
    }
}
